package com.yuzhihao.writejvm.clazz;

import com.yuzhihao.writejvm.format.ClassFormatEnum;
import com.yuzhihao.writejvm.format.PrintFormat;
import com.yuzhihao.writejvm.read.TypeFatory;
import com.yuzhihao.writejvm.read.Parse;
import lombok.Data;
import lombok.extern.log4j.Log4j2;

import java.io.DataInputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 魔法值
 *
 * @author yzh
 * @date 2021年11月29日18:32:13
 */
@Data
@Log4j2
public class AccessFlags implements Parse {

    private ClassFormatEnum cfe = ClassFormatEnum.access_flags;

    private int value;

    private List<String> flags;

    @Override
    public void parse(DataInputStream dis, ClassInfo ci) {
        try {
            this.value = Parse.byteToInt(cfe.getB(), dis);
            this.flags = TypeFatory.access_flags(this.value).stream().map(TypeFatory.Access::getFname).collect(Collectors.toList());
        } catch (IOException e) {
            log.error(e);
        }

        this.out(ci);
    }

    public void out(ClassInfo ci) {
        ci.setAccess_flags(this);
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append(PrintFormat.EMPTY).append("flags：");
        for (String flag : this.flags) {
            builder.append(flag).append(",");
        }
        builder.delete(builder.length()-1,builder.length());
        builder.append(System.lineSeparator());
        return  builder.toString();
    }

    public String access(){
        return flags.contains(TypeFatory.access_flag(1).getFname()) ? "public" : "";
    }

}
